package com.ctsi.oauth.manager;

import com.ctsi.auth.integration.authenticator.IntegrationAuthenticator;
import com.ctsi.auth.vcc.manager.UserAccountLockService;
import com.ctsi.commons.util.UtilValidate;
import com.ctsi.framework.organise.security.SecurityUser;
import com.ctsi.framework.organise.security.UserInfo;
import com.ctsi.organise.common.api.OrganiseFactoryBean;
import com.ctsi.organise.common.constant.AccountStatus;
import com.ctsi.organise.common.constant.PartyType;
import com.ctsi.organise.common.model.Organise;
import com.ctsi.organise.common.model.Person;
import com.ctsi.organise.common.model.UserLogin;
import com.ctsi.security.ISecurity;
import com.ctsi.security.domain.RolePermission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangjw
 */
@Service
public class SecurityUserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(SecurityUserDetailsServiceImpl.class);

    @Autowired
    private ISecurity iSecurity;

    @Autowired
    private UserAccountLockService userAccountLockService;

    private List<IntegrationAuthenticator> authenticators;

    @Autowired(required = false)
    public void setIntegrationAuthenticators(List<IntegrationAuthenticator> authenticators) {
        this.authenticators = authenticators;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserLogin userlogin = OrganiseFactoryBean.getInstance().getUserLoginProxy().findUserLoginByLoginName(username);

        if (userlogin == null) {
            logger.error("login name {} not found", username);
            throw new UsernameNotFoundException("用户名或密码错误!");
        }
        UserInfo info = new UserInfo();
        if (AccountStatus.DELETE.value.equals(userlogin.getStatusId()) || AccountStatus.DISABLE.equals(userlogin.getStatusId())) {
            logger.warn("账户 {} 被删除或被禁用", userlogin.getLoginName());
            return new SecurityUser(
                    userlogin.getLoginName(),
                    userlogin.getPassword(),
                    false,
                    true,
                    true,
                    true,
                    null
            );
        }
        if (AccountStatus.LOCK.value.equals(userlogin.getStatusId()) || userAccountLockService.isLock(username)) {
            logger.warn("账户{}被锁定", userlogin.getLoginName());
            return new SecurityUser(userlogin.getLoginName(),
                    userlogin.getPassword(),
                    true,
                    true,
                    true,
                    false,
                    null);
        }
        String userId = userlogin.getPartyId();
        info.setUserId(userId);
        info.setLoginId(userlogin.getId());
        info.setTenementId(userlogin.getTenementId());

        Person user = OrganiseFactoryBean.getInstance().getPersonServiceProxy().findPersonById(userId);
        info.setEmail(user.getEmail());
        info.setMobilePhone(user.getMobilePhone());
        info.setFullName(user.getFullName());

        Organise organ = OrganiseFactoryBean.getInstance().getPersonServiceProxy().getDefaultOrgan(userId);

        if (organ != null) {
            info.setDepartName(organ.getShortName());
            info.setDepartId(organ.getPartyId());
            if (PartyType.MINORGAN.value == organ.getPartyTypeId()) {
                info.setOrganName(UtilValidate.isEmpty(organ.getShortName()) ? organ.getOrganiseName() : organ.getShortName());
                info.setOrganId(organ.getPartyId());
            }
        }
        List<String> roles = iSecurity.getSecurityRoles(info.getLoginId());
        List<String> perms = iSecurity.getPersonRolePermission(info.getLoginId()).stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
        // TODO: 此处可以设置用户角色，有没有必要视具体情况而定
        //List<SRole> roles = (List<SRole>) OrganiseFactoryBean.getInstance().getRoleProxy().getPersonRoles(userId);
        //List<String> roleIds = roles.stream().map(role -> role.getRoleId()).collect(Collectors.toList());
        roles = roles.stream().map(s -> "ROLE_".concat(s)).collect(Collectors.toList());
        info.setRoles(roles);
        info.setPermissions(perms);
        return new SecurityUser(userlogin.getLoginName(),
                userlogin.getPassword(),
                true,
                true,
                true,
                true, info);
    }
}
